package tabuImpl.tsp.gene;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tabuImpl.tsp.algorithm.TabuSeachImpl;
import tabuImpl.tsp.tabuList.TabuListImpl;
import tabuImpl.util.TabuUtil;
import tabuInterface.algorithm.tabuList.TabuData;
import tabuInterface.algorithm.tabuList.TabuList;
import tabuInterface.gene.Gene;
import tabuInterface.gene.GeneNoParameter;
import tabuInterface.gene.Phen;

import java.util.Arrays;
import java.util.List;

@Component
public class TabuGene implements GeneNoParameter {

    private int []data;

    private TabuSeachImpl tabuSeach;

    @Autowired
    public TabuGene(@Value("#{'${tsp.testData}'.split(',')}") List<String> data, @Value("#{null}")TabuSeachImpl tabuSeach){
        this.data= data.stream().mapToInt(Integer::parseInt).toArray();
        this.tabuSeach=tabuSeach;
    }
    public TabuGene(int [] data,TabuSeachImpl tabuSeach){
        this.data= data;
        this.tabuSeach=tabuSeach;
    }

    @Override
    public Phen phen() {
        return new TabuPhen();
    }

    public int[] checkDiff(Gene newGene) {//检查两个基因型的不同 返回交换位置的数组
        int [] ans=new int[2];
        int now=0;
        int[] newGeneData=((TabuGene)newGene).data();
        int[] nowGeneData=this.data();
        for (int i=0;i<nowGeneData.length;i++)
            if(nowGeneData[i]!=newGeneData[i]){
                ans[now++]=i;
                if(now==2)
                    return ans;
            }
        return null;
    }

    @Override
    public Gene[] neighborhood() {//产生领域 在tsp中，
        //采用产生领域为动作空间 最终转换为gene[]
        //无参也可以获取
        TabuListImpl tabuList=(TabuListImpl) tabuSeach.getTabuList();
        int[] tdata=tabuList.getData();
        Gene[] ans= new Gene[tdata.length];
        int n=tabuList.getPointN();
        for (int i=0;i<tdata.length;i++){
            int[] t=this.data().clone();
            int t1=i/n,t2=i%n;
            TabuUtil.swap(t,t1,t2);
            ans[i]=new TabuGene(t,this.tabuSeach);
        }


        return ans;
    }

    public int[] data(){
        return data;
    }

}
